package jamie.example.io.nio.buffer;

import java.nio.ByteBuffer;

/**
 * 从缓存区中读取数据
 * 1. capacity：容量（长度）limit： 界限（最多能读/写到哪里）posotion：位置（读/写 * 哪个索引）
 * 2. 获取缓冲区里面数据之前，需要调用flip方法
 * 3. 再次写数据之前，需要调用clear方法，但是数据还未消失，等再次写入数据，被覆盖了 * 才会消失。
 * @author jamie
 */
public class GetBufferDemo {

    public static void main(String[] args) {
        //1.创建一个指定长度的缓冲区
        ByteBuffer allocate = ByteBuffer.allocate(10);
        allocate.put("0123".getBytes());
        System.out.println("position:" + allocate.position());  //4
        System.out.println("limit:" + allocate.limit());        //10
        System.out.println("capacity:" + allocate.capacity());  //10
        System.out.println("remaining:" + allocate.remaining());//6
        //切换读模式
        System.out.println("读取数据--------------");
        allocate.flip();
        System.out.println("position:" + allocate.position());  //4
        System.out.println("limit:" + allocate.limit());        //10
        System.out.println("capacity:" + allocate.capacity());  //10
        System.out.println("remaining:" + allocate.remaining());//6
        for(int i = 0; i < allocate.limit(); i++){
            System.out.println(allocate.get());
        }
        //读取完毕后.继续读取会报错,超过limit值
        // System.out.println(allocate.get());
        //读取指定索引字节
        System.out.println("读取指定索引字节--------------");
        System.out.println(allocate.get(1));

        System.out.println("读取多个字节--------------");

        // 重复读取
        allocate.rewind();
        byte[] bytes = new byte[4];
        allocate.get(bytes);
        System.out.println(new String(bytes));
        // 将缓冲区转化字节数组返回
        System.out.println("将缓冲区转化字节数组返回--------------");
        byte[] array = allocate.array();
        System.out.println(new String(array));
        // 切换写模式,覆盖之前索引所在位置的值
        System.out.println("写模式--------------");
        allocate.clear();
        allocate.put("abc".getBytes());
        System.out.println(new String(allocate.array()));
    }

}
